package com.uxsino.simo.indicator.retractor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.uxsino.commons.utils.config.ConfigProp;
import com.uxsino.simo.networkentity.EntityInfo;
import com.uxsino.simo.query.QueryContext;
import com.uxsino.simo.query.QueryTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 如果有字段设置，则根据字段进行解析，否则按照columnName 返回对应的数据集合
 */
public class DatasetRetractor extends ListValueRetractor {
    private static Logger logger = LoggerFactory.getLogger(DatasetRetractor.class);

    @ConfigProp(name = "recordset_num")
    private int datasetIndex = 1; // starts from 1, first data set by default

    @Override
    public Object doRetract(EntityInfo entity, QueryContext ctxt, QueryTemplate qt, Object obj) {
        ArrayList<Map<String, Object>> records = new ArrayList<Map<String, Object>>();
        if (null == obj) {
            return records;
        }
        ObjectMapper mapper = new ObjectMapper();
        MultiDataset md = mapper.convertValue(obj, new TypeReference<MultiDataset>(){});
        // Dataset nr = (Dataset) obj;
        if (md.size() < datasetIndex) {
            logger.error("recordset {} is required but onle {} recordset is returned", datasetIndex, md.size());
            return null;
        }

        Dataset nr = md.get(datasetIndex - 1);
        for (String[] row : nr.records) {
            HashMap<String, Object> fieldValues = new HashMap<String, Object>();
            if(columnEntries != null && !columnEntries.isEmpty()){
                for (ColumnEntry entry : columnEntries) {
                    Object value = null;

                    // <cloumn col_id="1" field="fieldName">
                    int col_num;

                    if (nr.columnNames.containsKey(entry.index)) {
                        col_num = nr.columnNames.get(entry.index);
                    } else {
                        try {
                            col_num = Integer.parseInt(entry.index.trim());
                        } catch (NumberFormatException e) {
                            logger.error("col_id: " + entry.index + " not found");
                            continue;
                        }
                    }
                    if (col_num < 1 || col_num > row.length) {
                        logger.error("column index out of range: " + entry.index);
                        continue;
                    }
                    String s = row[col_num - 1];
                    if (s != null) {
                        value = entry.retractor.retract(entity, ctxt, qt, s);
                        fieldValues.put(entry.field.getName(), value);
                    } else {
                        logger.warn("column index out of range:{} . value is null!", entry.index);
                    }

                }
            } else {
                nr.getColumnNames().forEach((name, col)->{
                    fieldValues.put(name, row[col-1]);
                });
            }
            records.add(fieldValues);

        }

        return records;
    }

}
